#this will be the script


run_analysis <- function(path_to_data){
	tidy <- read_and_combine(path_to_data)
	extracted <- extract_stdmean(tidy)
	bind <- bind_activity_label(path_to_data,extracted)
	updated <- update_var_names(bind) 
	updated
}

read_and_combine <- function(path_to_data){
f <-read.table(paste(path_to_data,"/","features.txt",sep=""))
ty <-read.table(paste(path_to_data,"/","test/y_test.txt",sep=""))
tsub <-read.table(paste(path_to_data,"/","test/subject_test.txt",sep=""))
tx <-read.table(paste(path_to_data,"/","test/X_test.txt",sep=""))
tny <-read.table(paste(path_to_data,"/","train/y_train.txt",sep=""))
tnsub <-read.table(paste(path_to_data,"/","train/subject_train.txt",sep=""))
tnx <-read.table(paste(path_to_data,"/","train/X_train.txt",sep=""))
#read test x, y, sub and train x, y sub
	names(tx) <- f[,2]
	names(ty) <- "Activities"
	names(tsub) <- "Subject"
	names(tnx) <- f[,2]
	names(tny) <- "Activities"
	names(tnsub) <- "Subject"
#combine test and train data
	tidy1 <- cbind(tsub,cbind(ty,tx))
	tidy2 <- cbind(tnsub,cbind(tny,tnx))
	tidy <- rbind(tidy1,tidy2)
	tidy
}

#extracts only the std and means, also reserve subject and
#activity
extract_stdmean <- function(tidy){
	stdmean <- tidy[,grep("(std\\())|(mean\\())",names(tidy))]
	stdmean <- stdmean[,grep("^t",names(stdmean))]
	stdmean <- stdmean[,grep("[X,Y,Z]",names(stdmean))]
	stdmean <- cbind(tidy[,1:2],stdmean)
	stdmean
}

#read the activity_labels.txt file, then join the data set 
#together
bind_activity_label <- function(path_to_data,extracted){
library(plyr)
f <- read.table(paste(path_to_data,"/",
	"activity_labels.txt",sep=""))
names(f) <- c("Activities","Activity Lable")
joined <- join(extracted,f,by="Activities")
joined[,2] <- joined[,33]
joined <- joined[,1:32]
joined
}

#to update the variable names for the tidy data
#the data should only contains the mean and std
#for each measurement.
update_var_names <- function(tidy){
names(tidy) <- c("Subject",
	"Activities",
	"Body Acc Mean X",
	"Body Acc Mean Y",
	"Body Acc Mean Z",
	"Body Acc Std X",
	"Body Acc Std Y",
	"Body Acc Std Z",
	"Gravity Acc Mean X",
	"Gravity Acc Mean Y",
	"Gravity Acc Mean Z",
	"Gravity Acc Std X",
	"Gravity Acc Std Y",
	"Gravity Acc Std Z",
	"Body Acc Jerk Mean X",
	"Body Acc Jerk Mean Y",
	"Body Acc Jerk Mean Z",
	"Body Acc Jerk Std X",
	"Body Acc Jerk Std Y",
	"Body Acc Jerk Std Z",
	"Body Gyro Mean X",
	"Body Gyro Mean Y",
	"Body Gyro Mean Z",
	"Body Gyro Std X",
	"Body Gyro Std Y",
	"Body Gyro Std Z",
	"Body Gyro Jerk Mean X",
	"Body Gyro Jerk Mean Y",
	"Body Gyro Jerk Mean Z",
	"Body Gyro Jerk Std X",
	"Body Gyro Jerk Std Y",
	"Body Gyro Jerk Std Z")
	tidy
}
